﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Collections;
using Microsoft.Win32;

namespace eBirdAttend
{
    public partial class LeaveMgt : UserControl
    {
        SqlConnection _sqlcon;
        SqlCommand _sqlcmd;
        DataSet ds;
        DataSet ds1;
        DataTable dt;
        DataTable dt1;
        SqlDataAdapter _sqladt;
        SqlDataReader _sqldr;
        ArrayList _arrEmpID = new ArrayList();
        ArrayList _arrMastCode=new ArrayList();
        string _strCon;
        #region Properties
        int _shiftCode;
        public int ShiftCode
        {
            get { return _shiftCode; }
            set { _shiftCode = value; }
        }        
        
      
        #endregion Properties

        private static bool _recursion = false;        
        //string _strCon =  Properties.Settings.Default.constr;
        public LeaveMgt()
        {
            InitializeComponent();
            FillConnectionStr();            
        }

        private void LeaveMgt_Load(object sender, EventArgs e)
        {
            SelectShift();
            SelectEmployee();
            SelectLeaveType();
            FillLeaveLog();
        }

        private void FillLeaveLog()
        {
            try
            {
                dataGridView1.Columns.Clear();
                
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select EmpFirstName + ' ' + EmpLastName AS Name,AttnDate AS Date,LtName as LeaveType, LRNote as Description,RecordNo from LeaveReportView";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                if (ds != null)
                    dataGridView1.DataSource = ds.Tables[0].DefaultView;

                if (dataGridView1.Rows.Count == 0)
                {
                    BuildNoRecords(dataGridView1, ds, "No Records Found");
                    return;
                }

                //Add Checkbox column....
                DataGridViewCheckBoxColumn chkColumn = new DataGridViewCheckBoxColumn();
                chkColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                chkColumn.Width = 120;
                chkColumn.HeaderText = "Select ALL";
                dataGridView1.Columns.Insert(0,chkColumn);
                Rectangle rect = dataGridView1.GetCellDisplayRectangle(0, -1, true);
                rect.X = rect.Location.X + (rect.Width / 2);
                CheckBox chkHeader = new CheckBox();
                chkHeader.Name = "checkboxHeader";
                chkHeader.Size = new Size(18, 18);
                chkHeader.Location = new Point(115,10);
                chkHeader.CheckedChanged += new EventHandler(chkHeader_CheckedChanged);
                dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                dataGridView1.ColumnHeadersHeight = 40;
                
                dataGridView1.Controls.Add(chkHeader);
                dataGridView1.Columns[5].Visible = false;

               
            }
            catch (SqlException ex)
            {
            }
        }

        private void BuildNoRecords(DataGridView dg,DataSet dd,string str)
        {
            try
            {
                if (dd.Tables[0].Rows.Count == 0)
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    dg.DataSource = ds;
                    dg.Columns.Clear();
                    DataGridViewColumn col = new DataGridViewColumn();
                    DataGridViewCell cell = new DataGridViewTextBoxCell();
                    col.CellTemplate = cell;
                    col.HeaderText = "No records Found";
                    col.Name = "No records Found";
                    col.Visible = true;
                    col.Width = 160;
                    dg.Columns.Add(col);
                    dg.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                    dg.ColumnHeadersHeight = 40;
                }
            }
            catch (Exception)
            {
            }
        }
       
        void chkHeader_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1[0, i].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
            }
            dataGridView1.EndEdit();

        }

        private void SelectLeaveType()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select LtName,LtID from LeaveTypesLookUp";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                if (ds == null)
                {
                    return;
                }
                int i = (ds.Tables[0].Rows.Count) - 1;
                dt1 = new DataTable();
                DataRow dr1;
                dt1.Columns.Add("LtName");
                dt1.Columns.Add("LtID");
                dr1 = dt1.NewRow();
                dr1["LtName"] = "ALL";
                dr1["LtID"] = 0;
                dt1.Rows.Add(dr1);
                while (i >= 0)
                {
                    dr1 = dt1.NewRow();
                    dr1["LtName"] = ds.Tables[0].Rows[i][0];
                    dr1["LtID"] = ds.Tables[0].Rows[i][1];
                    dt1.Rows.Add(dr1);
                    i--;
                }

                BindingSource BindingSource1 = new BindingSource();
                BindingSource1.DataSource = dt1.DefaultView;
                cmbLeave.DataSource = BindingSource1;
                cmbLeave.DisplayMember = dt1.Columns[0].ColumnName;
                cmbLeave.ValueMember = dt1.Columns[1].ColumnName;
                cmbLeave.Text = dt1.Rows[0][0].ToString();
                cmbLeave.SelectedValue = dt1.Rows[0][1];
                _sqlcon.Close();
            }
            catch (Exception ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("Select the leave type : " + ex.Message.ToString());
            }
        }

        private void FillConnectionStr()
        {
            //Connection string stored in REgistry
            RegistryKey regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\eBird\\eOffice1.0");
            if (regKey != null)
            {
                _strCon = regKey.GetValue("ConctString").ToString();
            }
        }

        private void SelectEmployee()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select distinct (EmpFirstName + ' ' + EmpLastName) as Name,EmpId from EmployDetails";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                _sqlcon.Close();

                chkEmployList.Items.Clear();
                if(ds.Tables[0].Rows.Count > 0)
                chkEmployList.Items.Add("(All)");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    chkEmployList.Items.Add(dr[0], CheckState.Unchecked);
                    //chkEmployList.Items.Add(dr[1],CheckState.Unchecked);      
                }
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("Select all employees  : "+ex.Message.ToString());
            }

        }

        private void chkEmployList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            // Recursion breaker (calling SetItemCheckState will re-fire this event)
            if (_recursion)
                return;

            _recursion = true;

            // If the "(All)" item is clicked, apply the new value to all items
            if (e.Index == 0)
                CheckAllItems(e.NewValue);

            // If any item is unchecked, then uncheck the "all" item
            else if (e.NewValue == CheckState.Unchecked)
                chkEmployList.SetItemCheckState(0, e.NewValue);

            _recursion = false;
        }

        private void CheckAllItems(CheckState value)
        {
            for (int i = 0; i < chkEmployList.Items.Count; i++)
            {
                chkEmployList.SetItemCheckState(i, value);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            lstEmploy.Items.Clear();
            foreach (int i in chkEmployList.CheckedIndices)
            {
                if(!chkEmployList.Items[i].ToString().Contains("All"))
                lstEmploy.Items.Add(chkEmployList.Items[i].ToString());
                //lstEmploy.Items.Remove("(ALL)");
            }
            if(lstEmploy.Items.Count>0)
            panel2.Visible = true;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            foreach (int i in lstEmploy.SelectedIndices)
            {
                object itemToRemove = lstEmploy.Items[i];
                lstEmploy.Items.Remove(itemToRemove);
            }
            if (lstEmploy.Items.Count > 0)
                panel2.Visible = true;
            else
                panel2.Visible = false;
        }

        private void SelectShift()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select ShName,ShId from ShiftDetails";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                if (ds == null)
                {
                    return;
                }
                int i = (ds.Tables[0].Rows.Count) - 1;
                dt1 = new DataTable();
                DataRow dr1;
                dt1.Columns.Add("ShName");
                dt1.Columns.Add("ShID");
                dr1 = dt1.NewRow();
                dr1["ShName"] = "ALL";
                dr1["ShID"] = 0;
                dt1.Rows.Add(dr1);
                while (i >= 0)
                {
                    dr1 = dt1.NewRow();
                    dr1["ShName"] = ds.Tables[0].Rows[i][0];
                    dr1["ShID"] = ds.Tables[0].Rows[i][1];
                    dt1.Rows.Add(dr1);
                    i--;
                }

                BindingSource BindingSource1 = new BindingSource();
                BindingSource1.DataSource = dt1.DefaultView;
                cmbShiftWise.DataSource = BindingSource1;
                cmbShiftWise.DisplayMember = dt1.Columns[0].ColumnName;
                cmbShiftWise.ValueMember = dt1.Columns[1].ColumnName;
                cmbShiftWise.Text = dt1.Rows[0][0].ToString();
                cmbShiftWise.SelectedValue = dt1.Rows[0][1];
                _sqlcon.Close();
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("For selecting shift  : "+ex.Message.ToString());
            }        
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (lstEmploy.Items.Count > 0)
            {
                if (cmbLeave.Text == "ALL")
                {
                    MessageBox.Show("Please select the leave type");
                    return;
                }
                if (lstEmploy.Items.ToString() == "(ALL)")
                    return;
                SelectEmpID();
                LeaveAdded();
            }
            else
            {
                MessageBox.Show("Please select the employees");
            }
        }
        

        private void SelectEmpID()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcon.Open();
                for (int i = 0; i < lstEmploy.Items.Count; i++)
                {
                    _sqlcmd.CommandText = "select EmpId from EmployDetails where (EmpFirstName + ' ' + EmpLastName) like '%" + lstEmploy.Items[i].ToString().Trim() + "%'";
                    _sqldr = _sqlcmd.ExecuteReader();
                    while (_sqldr.Read())
                    {
                        _arrEmpID.Add(_sqldr[0].ToString());                        
                    }
                    _sqldr.Close();
                }
                _sqlcon.Close();
            }
            catch (SqlException ex)
            {
                if (!_sqldr.IsClosed)
                    _sqldr.Close();
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("For selecting employee id :  "+ex.Message.ToString());
            }
        }

        private void LeaveAdded()
        {
            try
            {
               
                for (int i = 0; i < _arrEmpID.Count; i++)
                {
                    if (CheckShiftStatus(_arrEmpID[i].ToString()))
                    {
                        DateTime _dtFrom = dtFrom.Value.Date;
                        DateTime _dtTo = dtTo.Value.Date;

                        if (!_sqldr.IsClosed)
                            _sqldr.Close();
                        _sqlcon = new SqlConnection(_strCon);
                        _sqlcmd = new SqlCommand();
                        _sqlcmd.Connection = _sqlcon;
                        _sqlcon.Open();
                        while (_dtFrom <= _dtTo)
                        {
                            _sqlcmd.CommandText = "insert into DateWiseAttnData(dtEmpID,dtDate,dtLeaveStatus) values ('" + _arrEmpID[i].ToString() + "', '" + _dtFrom + "',"+ cmbLeave.SelectedIndex + ");select SCOPE_IDENTITY();"; 
                            object _objID=_sqlcmd.ExecuteScalar();
                            int id = Convert.ToInt32(_objID.ToString());
                            if (id > 0)
                            {
                                _sqlcmd.CommandText = "insert into LeaveReasons(LRRecordNo,LRNote) values ('" + id + "','" + txtNote.Text + "')";
                                _sqlcmd.ExecuteNonQuery();
                            }
                            _dtFrom= _dtFrom.AddDays(1);
                        }
                        _sqlcon.Close();

                    }                   
                }
                MessageBox.Show("Leave Entered Successfully");
                lstEmploy.Items.Clear();
                SelectShift();
                SelectEmployee();
                CheckAllItems(CheckState.Unchecked);
                ClearControls();
                FillLeaveLog();
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("Leave Inserting :  " +ex.Message);
            }
        }

        private void ClearControls()
        {
            cmbLeave.SelectedIndex = 0;
            dtFrom.Value = DateTime.Now;
            dtTo.Value = DateTime.Now;
            txtNote.Text = "";
        }
        
        private bool CheckShiftStatus(string _strEmpID)
        {

            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcon.Open();
                _sqlcmd.CommandText = "select EmpID from EmployDetails where EmpID= '" + _strEmpID + "'";
                _sqldr = _sqlcmd.ExecuteReader();
                if (_sqldr.Read())
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite("Check Shift Status  :  " +ex.Message.ToString());
                return false;
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void btnRemovAll_Click(object sender, EventArgs e)
        {
            lstEmploy.Items.Clear();
            panel2.Visible = false;
        }

        private void cmbShiftWise_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbShiftWise.Text != "ALL")
            {
                chkEmployList.Items.Clear();
                try
                {
                    _sqlcon = new SqlConnection(_strCon);
                    _sqlcmd = new SqlCommand();
                    _sqlcmd.Connection = _sqlcon;
                    _sqlcmd.CommandText = "select distinct (EmpFirstName + ' ' + EmpLastName) as Name,EmpId from EmployDetails where EmpShiftId='" + cmbShiftWise.SelectedValue + "'";
                    _sqladt = new SqlDataAdapter(_sqlcmd);
                    ds1 = new DataSet();
                    _sqladt.Fill(ds1);
                    _sqlcon.Close();

                    chkEmployList.Items.Clear();
                    if(ds1.Tables[0].Rows.Count > 0)
                    chkEmployList.Items.Add("(All)");
                    foreach (DataRow dr in ds1.Tables[0].Rows)
                    {
                        chkEmployList.Items.Add(dr[0], CheckState.Unchecked);
                        //chkEmployList.Items.Add(dr[1],CheckState.Unchecked);      

                    }
                }
                catch (SqlException ex)
                {
                    if (_sqlcon.State == ConnectionState.Open)
                        _sqlcon.Close();
                    LogWrite("Select employees on the basis of shift  :  "+ex.Message.ToString());
                }
            }
            else
            {
                SelectEmployee();
            }
        }

        public void LogWrite(string Log)
        {
            try
            {
                string strFileName = "LogFile.txt";
                StreamWriter sWriter = new StreamWriter(strFileName, true);
                DateTime dateTime = DateTime.Now;
                sWriter.WriteLine(dateTime + "\r\t" + Log + "\r\n");
                sWriter.Close();
                sWriter.Dispose();
            }
            catch (Exception ex)
            {
                //NOTHING TO DO....
            }
        }
        

        private void btnLvCancel_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("Are you sure you want to delete?", "Delete confirmation",
                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.No)
                return;

            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                string status="";
                if (dr.Cells[0].Value != null)
                {
                    status = dr.Cells[0].Value.ToString();
                }
                if (status == "True")
                {
                    LeaveDeleted(dr.Cells[5].Value.ToString());
                }
            }
            FillLeaveLog();
        }

        private void LeaveDeleted(string _strrecordNo)
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcon.Open();
                _sqlcmd.CommandText = "delete from DateWiseAttnData where RecordNo= '" + _strrecordNo + "'";
               _sqlcmd.ExecuteNonQuery();
               _sqlcon.Close();
            }
            catch (SqlException ex)
            {
                if(_sqlcon.State==ConnectionState.Open)
                    _sqlcon.Close();
            }

        }

       

        


           


      
    }

}
